import React, {PureComponent} from 'react';
import styles from './index.less';
import ProTable from '@ant-design/pro-table';
import { DatePicker, Button } from 'antd'

function initTotalList(columns) {
    const totalList = [];
    columns.forEach((column) => {
        if (column.needTotal) {
            totalList.push({...column, total: 0});
        }
    });
    return totalList;
}

class StandardTable extends PureComponent {
    formRef = React.createRef();

    constructor(props) {
        super(props);
        const {columns} = props;
        const needTotalList = initTotalList(columns);

        this.state = {
            selectedRowKeys: [],
            needTotalList,
        };

    }

    static getDerivedStateFromProps(nextProps) {
        // clean state
        if (nextProps.selectedRows.length === 0) {
            const needTotalList = initTotalList(nextProps.columns);
            return {
                selectedRowKeys: [],
                needTotalList,
            };
        }
        return null;
    }

    componentDidMount(){
        var div = document.getElementsByClassName("dataList");
        this.setState({clientWidth: div.length ? div[0].offsetWidth: document.body.clientWidth})

    }

    handleRowSelectChange = (selectedRowKeys, selectedRows) => {
        let {needTotalList} = this.state;
        needTotalList = needTotalList.map((item) => ({
            ...item,
            total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
        }));
        const {onSelectRow} = this.props;
        if (onSelectRow) {
            onSelectRow(selectedRows);
        }

        this.setState({selectedRowKeys, needTotalList});
    };

    handleTableChange = (pagination, filters, sorter) => {
        const {onChange} = this.props;
        if (onChange) {
            onChange(pagination, filters, sorter);
        }
    };

    cleanSelectedKeys = () => {
        this.handleRowSelectChange([], []);
    };

    render() {
        const {selectedRows, ...otherProps} = this.props;
        const {selectedRowKeys, needTotalList} = this.state;
        let tableProps = {}
        if (otherProps.tableSetting) {
            tableProps.onColumnsStateChange = this.props.handleSettingColumnChange
        }
        let {
            data: {list, pagination},
            loading,
            columns,
            rowKey,
            bordered,
        } = this.props;
        window.onresize = ()=>{
            var div = document.getElementsByClassName("dataList");
            this.setState({clientWidth: div.length ? div[0].offsetWidth: document.body.clientWidth})
        }
        let paginationProps = {
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            pageSize: 10,
            pageSizeOptions: ['10', '20', '50', '100', '200', '500', '1000'],
            ...pagination,
        };
        if (otherProps.pagination === false) {
            paginationProps = false;
        }
        const rowSelection = otherProps.showSelect && {
            selectedRowKeys,
            onChange: this.handleRowSelectChange,
            getCheckboxProps: (record) => ({
                disabled: record.disabled,
            }),
        };
        let tableWidth;
        if (document.getElementById('table')) {
            tableWidth = document.getElementById('table').offsetWidth;
        }
        columns = columns.map((item, index) => {
            if (item.type === 'Select') {
                let dict = {};

                if (item.dict) {
                    Object.keys(item.dict).forEach((key) => {
                        let value = {};
                        value['text'] = item.dict[key].remark;
                        value[item.key] = item.dict[key].value;
                        return (dict[key] = value);
                    });
                }
                return {
                    ...item,
                    tip: item.extra,
                    renderFormItem: !item.notRenderFormItem && item.renderInput,
                    valueEnum: dict,
                    valueType: 'select',
                    showSorterTooltip: false,
                    fieldProps: {
                        allowClear: true,
                        showSearch: true,
                        ...item.props,
                        extra:undefined,
                        optionFilterProp: 'label',
                    },
                };
            } else {
                if (item.type === 'DatePicker') {
                    return {
                        ...item,
                        tip: item.extra,
                        showSorterTooltip: false,
                        renderFormItem:  (items, { type, defaultRender, ...rest }, form) => {
                            return <DatePicker allowClear={item.props.allowClear===false ? false: true} style={{width: '100%'}}  format={item.props && item.props.format} {...item.props} showTime={item.props && (item.props.showTimes ||  item.props.type==='showTime') }></DatePicker>
                        },
                        valueType: 'dateTime',
                        ...item.props,
                    };
                } else {
                    return {
                        ...item,
                        tip: item.extra,
                        showSorterTooltip: false,
                        renderFormItem: !item.notRenderFormItem && item.renderInput,
                    };
                }
            }
        });
        return (
            <div className={styles.standardTable}>
                <ProTable
                    id={'table'}
                    loading={loading}
                    bordered={true}
                    dataSource={list}
                    onReset={this.props.handleFormReset}
                    onSubmit={this.props.handleSearch}
                    scroll={{x: 'max-content'}}
                    size={'middle'}
                    {...otherProps}
                    rowSelection={rowSelection}
                    columns={columns}
                    pagination={paginationProps}
                    formRef={otherProps.form}
                    request={async (params = {}, sort, filter) => {
                        this.setState({loading: true});
                        let res = await otherProps.refreshList(
                            otherProps.form &&
                            otherProps.form.current &&
                            otherProps.form.current.getFieldsValue(),
                        );
                        return {
                            data: [],
                            success: true,
                            total: paginationProps.total,
                        };
                    }}
                    editable={{
                        type: 'multiple',
                    }}
                    columnsState={{
                        persistenceKey: 'pro-table-singe-demos',
                        persistenceType: 'localStorage',
                    }}
                    toolBarRender={otherProps.toolBarRender}
                    onChange={this.handleTableChange}
                    rowKey={rowKey || 'id'}
                    search={
                        
                        otherProps.search !== undefined &&otherProps.search !== true
                            ? otherProps.search
                            : {
                                labelWidth: otherProps.searchLabelWidth,
                                span:   this.state.clientWidth > 1600?{
                                    xs: 6,
                                    sm: 6,
                                    md: 6,
                                    lg: 6,
                                    xl: 4,
                                    xxl: 4,
                                  }: {
                                    xs: 6,
                                    sm: 6,
                                    md: 6,
                                    lg: 6,
                                    xl: 6,
                                    xxl: 6,
                                  },
                            }
                    }
                    form={{
                        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
                        syncToUrl: (values, type) => {
                            if (type === 'get') {
                                return {
                                    ...values,
                                    created_at: [values.startTime, values.endTime],
                                };
                            }
                            return values;
                        },
                    }}
                    headerTitle={otherProps.operationBar}
                    dateFormatter="string"
                    toolbar={{ actions: [otherProps.other && otherProps.other.renderToolbar] }}
                    options={{ fullScreen: true, reload: otherProps.search === false, setting: otherProps.tableSetting ?? false, density: false }}
                    tableExtraRender={() => {
                        return otherProps.other ? otherProps.other.renderOpeation : <div></div>;
                    }}
                    {...tableProps}
                />
            </div>
        );
    }
}

export default StandardTable;
